package com.CRApp.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import com.CRApp.pojo.Posts;
import com.CRApp.mapper.PostsMapper;
import com.CRApp.service.PostsService;
import com.CRApp.pojo.PostDetailsDTO;
import com.CRApp.pojo.Comment;
import com.CRApp.pojo.CommentDTO;

@Service
public class PostsServiceImpl implements PostsService {

    @Autowired
    private PostsMapper postsMapper;

    @Override
    public List<Posts> getPostsList(Integer currentUserId) {
        return postsMapper.getPostsList(currentUserId);
    }

    @Override
    public PostDetailsDTO getPostDetails(Integer postId) {
        return postsMapper.getPostDetails(postId);
    }

    @Override
    public List<Comment> getPostComments(Integer postId) {
        return postsMapper.getPostComments(postId);
    }

    @Override
    public void addComment(CommentDTO commentDTO, Integer currentUserId) {
        // 创建新的评论对象
        Comment comment = new Comment();
        comment.setPostId(commentDTO.getPostId());
        comment.setUserId(currentUserId);
        comment.setContent(commentDTO.getContent());
        comment.setParentCommentId(commentDTO.getParentCommentId());

        // 保存评论
        postsMapper.addComment(comment);
    }

    @Override
    @Transactional  // 添加事务注解，确保推文和图片同时保存成功
    public Integer createPost(Posts post, List<String> imageUrls) {
        // 1. 插入推文
        postsMapper.insertPost(post);
        Integer postId = post.getPostId();  // 获取自动生成的ID
        
        // 2. 如果有图片，插入图片记录
        if (imageUrls != null && !imageUrls.isEmpty()) {
            postsMapper.insertPostImages(postId, imageUrls);
        }
        
        return postId;
    }

    @Override
    public boolean isCollected(Integer userId, Integer postId) {
        return postsMapper.checkCollection(userId, postId);
    }

    @Override
    public boolean toggleCollection(Integer userId, Integer postId) {
        boolean isCollected = isCollected(userId, postId);
        if (isCollected) {
            postsMapper.removeCollection(userId, postId);
            return false;
        } else {
            postsMapper.addCollection(userId, postId);
            return true;
        }
    }

    @Override
    public List<Posts> getUserCollections(Integer userId) {
        return postsMapper.getUserCollections(userId);
    }
}
